<template>
  <basic-container v-loading="saveLoading">
    <div style="width:100%;min-height: 50px;padding-left:5px;display: inline-block;">
      <el-container>
        <el-container>
          <el-aside width="100px">
            <el-button type="primary" @click="updateRealityLineTpl" style="float: left;">保存</el-button>
          </el-aside>
        </el-container>
      </el-container>
    </div>
    <template>
      <div style="background:#fff;height: 50px;line-height: 50px;margin-bottom: 10px">
        <div class="pull-auto"  style="text-align: center;font-size: 16px;color:#3478f5;margin-right:10px">
          <div class="block">
            产线模板名称：{{lineName}}
          </div>
        </div>
      </div>
      <div class="form-designer">
        <el-container style="border: #e0e0e0 solid 1px;border-top:none">
          <el-aside width="240px">
            <el-header style="z-index:100;height:50px;text-align: center;line-height: 50px;width:240px;position: absolute;background: #fff">工位</el-header>
            <div style="height:800px;margin-top:45px">
              <!--工位菜单-->
              <workPositionMenu/>
            </div>
          </el-aside>
          <el-main class="demo" style="border-left: #e0e0e0 solid 1px;">
            <avue-flow :height="800"
                       width="100%"
                       ref="flow"
                       :option="option"
                       v-model="flowForm">
              <template #header="{node}" >
                  <el-tooltip class="item" effect="dark" :content="`工位(`+(node || {}).name+`)`" placement="top-start">
                     <span style="width:145px;white-space: nowrap;overflow: hidden;display: inline-block;vertical-align: bottom;text-overflow: ellipsis;">
                        工位({{(node || {}).name}})
                    </span>
                  </el-tooltip>
                  <div style="float: right;margin-right: 5px">
                    <el-tooltip class="item" effect="dark" content="添加工序" placement="top">
                      <i class="el-icon-plus" @click="openProcessDialog(node)" style="cursor: pointer;font-size:13px;margin-top: -2px;color:#403f3f;"></i>
                    </el-tooltip>
                    <el-divider direction="vertical"></el-divider>
                    <el-tooltip class="item" effect="dark" content="删除工位" placement="top-start">
                        <i class="el-icon-delete"  style="cursor: pointer;line-height: 30px;" @click="deleteNode(node)"></i>
                    </el-tooltip>
                </div>
              </template>
              <template slot-scope="{node}">
                <el-collapse :ref="node.id+`Ref`"  v-model="showActive[node.id]" :style="{width:'100%',zIndex:zIndexStyle}"  @mouseover.native="handleMouseEnter(node.id)"  @mouseout.native="handleMouseLeave(node.id)">
                  <el-collapse-item title="工序信息" name="1">
                    <el-descriptions  class="margin-top"  style="width: 100%;" title="" :column="1" size="small" border >
                        <el-descriptions-item  label="工序" :labelStyle="{'width': '50px'}"
                          v-model="`process_`+node.id"
                          v-for="(item, index) in workPositionProcessItem[node.id]">

                          {{item.processName}}

                        </el-descriptions-item>
                    </el-descriptions>
                  </el-collapse-item>
                 </el-collapse>
              </template>
            </avue-flow>

          </el-main>
        </el-container>
      </div>
    </template>

    <!--工序添加弹窗页面-->
    <el-dialog title=""
               :visible.sync="addProcessDialogVisible"
               width="50%"
               height="600"
               lock-scroll
               v-dialogDrag
               append-to-body
               :close-on-click-modal="false"
               v-if="addProcessDialogVisible"
               :fullscreen="addProcessDialogFull">
      <el-backtop target=".el-card__body .el-dialog__wrapper .el-dialog" :right="15" :bottom="20" :visibility-height="1" />
      <el-backtop :bottom="60"></el-backtop>
      <template slot="title">
        <div class="avue-crud__dialog__header">
          <span class="el-dialog__title">
              <span style="display:inline-block;background-color: #3478f5;width:3px;height:20px;margin-right:5px; float: left;margin-top:2px"></span>
              {{workPositionName}}-工序信息
          </span>
          <div class="avue-crud__dialog__menu" style="cursor: pointer;margin-top: -2px;margin-right: 10px;" @click="addProcessDialogFull? addProcessDialogFull=false: addProcessDialogFull=true">
              <i class="el-icon-full-screen"></i>
          </div>
        </div>
      </template>
      <!--工序菜单-->
      <div style="width: 100vh;display: inline-block;margin-top: 10px;margin-bottom: 10px">
        <el-input placeholder="输入关键字进行过滤" v-model="filterText" style="width:60vh;float:left;"></el-input>
        <el-button type="primary" @click="getCheckedProcess" style="float:left;margin-left: 10px">确认</el-button>
      </div>
      <el-tree
        ref="processTree"
        class="filter-tree el-dialog-height"
        :data="processTree"
        :props="processProps"
        node-key="id"
        show-checkbox
        check-strictly
        check-on-click-node
        :filter-node-method="filterNode"
        >
      </el-tree>
    </el-dialog>

  </basic-container>
</template>

<script>
import {fetchMenuTree } from '@/api/pfoc/pfocprocess'
import {updateLineTpl, getLineTplInfo} from '@/api/pfoc/realityproductlinetemplate'
import workPositionMenu from '@/views/pfoc/workposition/workPosition-menu'


export default {
    name: "edit-line-tpl",
    props:{
        lineId:{//产线模板ID
            type:String
        },
    },
    components: {
      workPositionMenu,
    },
    provide() {
      return {
        workPositionAddThis: this
      }
    },
    data() {
        return {
            count: 0,
            nodeCount:0,//节点下标
            form: [],//提交时数据集合
            flowForm:'',
            option: {
                name: null,
                nodeList: [],//工位节点集合
                lineList: [],//工位各节点指向顺序集合
            },
            coveringJson:[],//节点删除后补位集合
            lineName:null,//产线名称
            saveLoading:false,//保存时遮罩开关
            processTree:[],//工序集合
            workPositionProcessItem: {},//存储工位对应工序的二位数组
            processProps:{
                   id: 'id',
                   label: 'label',
                   children: 'children',
                   disabled: function (data, node) {//带子级的节点不能选中
                      if(data.processType !== '1') {
                        return true
                      } else {
                        return false
                      }
                    }
            },
            filterText: '',//过滤
            addProcessDialogVisible:false,//工序添加弹窗开关
            addProcessDialogFull:false,//工序添加弹窗放大缩小
            workPositionName:null,//工位名称(用于工序添加)
            workPositionId:null,//工位ID(用于工序添加)
            nodeId:null,//工位节点ID(用于工序添加)
            zIndexStyle:"",
            showActive:[],//属性展示model集合
            lineTplDetailsDelIds:[],//存储需要删除的节点工位ID（即已有工序删除ID）
            mainData:{},//产线模板主数据
            subData:[],//产线模板详情数据
        };
    },
   watch: {
      filterText(val) {
        this.$refs.processTree.filter(val);
      }
    },
    created() {
        //获取工序
        this.getMenuTree();
    },
    computed: {
        nodeList () {
            return this.option.nodeList
        }
    },
    mounted() {
        this.nodeCount = this.option.nodeList.length;//初始化节点下标
    },
    methods: {
        getRealityProductLineTpl(){
            if(!this.validatenull(this.lineId)) {
                getLineTplInfo(this.lineId).then(response => {
                    this.$refs.flow.resetPlumb();
                    let data = response.data.data;
                    //主表数据
                    this.mainData= data.lineTpl;//主数据
                    //子表数据
                    this.subData = data.lineTplDetails;//子表数据
                    //产线模板名称
                    this.lineName = this.mainData.lineName;
                    //设置反显工位
                    this.option.nodeList = JSON.parse(this.mainData.processNodes);
                    //设置反显工位指向顺序
                    this.option.lineList =  JSON.parse(this.mainData.processNodeLine);
                    this.coveringJson = JSON.parse(this.mainData.coveringJson);
                    //初始化节点下标
                    var n =  this.option.nodeList[ this.option.nodeList.length-1].id;
                    this.nodeCount = parseInt(n.split("node")[1])+1;
                    //从子表数据中根据nodeId字段将对应的workPositionProcessItem填入到页面的workPositionProcessItem二位数组中
                    for(var i=0;i<this.subData.length;i++){
                        var nodeId = this.subData[i].nodeId;
                        var item =JSON.parse(this.subData[i].workPositionProcessItem);
                        this.$set(this.workPositionProcessItem,nodeId, item);//添加工序集合
                    }
                    //重新初始化flow组件
                    this.$refs.flow.init();
                }).catch(() => {
                    this.saveLoading = false
                })
            }
        },
          /**打开添加工序窗口*/
        openProcessDialog(node){
          this.addProcessDialogVisible=true;
          this.workPositionName = node.name;
          this.workPositionId = node.mark;
          this.nodeId = node.id;
          const checkedNodes = this.workPositionProcessItem[node.id];
          if(!this.validatenull(checkedNodes)) {
            //设置反显
            this.$nextTick(() => {
              this.$refs.processTree.setCheckedNodes(this.workPositionProcessItem[node.id]);
            });
          }
        },
        //搜索过滤节点
        filterNode(value, data) {
          if (!value) return true;
          return data.label.indexOf(value) !== -1;
        },
        //存储选中的工序放入集合
        getCheckedProcess() {
          const checkedNodes = this.$refs.processTree.getCheckedNodes();
          var arry =[];
          for (var i = 0; i < checkedNodes.length; i++) {
            var obj = {};
            obj.id = checkedNodes[i].id; // 工序ID
            obj.label = checkedNodes[i].label; // 工序名称
            obj.processName = checkedNodes[i].processName;//工序名称
            obj.workshopSection = checkedNodes[i].workshopSection; // 工序所属工段
            arry.push(obj);
          }
          this.$set(this.workPositionProcessItem, this.nodeId, arry);//添加工序集合
          this.$set(this.showActive, this.nodeId, ['1']);//添加属性展示
          this.workPositionName = null;
          this.workPositionId = null;
          this.nodeId = null;
          this.addProcessDialogVisible = false;//关闭工序添加弹窗
        },
        /**获取工序*/
       getMenuTree() {
          this.loading = true
          fetchMenuTree(this.queryParams).then(response => {
            this.processTree = response.data.data
          })
        },
       /* /!**添加工位*!/
        addWorkPositionNode(name,id){//工位名称，工位ID
            var left = 0;
            if ((parseInt(this.nodeCount / 4))%2===0){
              left = (this.nodeCount % 4)*300
            }else {
              left = ((3-this.nodeCount % 4)*300)
            }
            var top = parseInt(this.nodeCount / 4)*150
            this.$refs.flow.addNode(name,id,this.nodeCount,left,top);//添加节点
            //画线
            if(this.nodeList.length>1) {
              var t = this;
              var index = this.nodeList.findIndex(item => item.id === "node"+t.nodeCount);
              var from = this.nodeList[index - 1].id;
              var to = this.nodeList[index].id;
              this.$nextTick((function() {
                this.$refs.flow.drawLines({"from": from, "to": to})
              }));
            }
          this.nodeCount=this.nodeCount+1;//更新节点下标
        },*/
        addWorkPositionNode(name,id){//工艺名称，工艺ID
          if (this.coveringJson.length > 0) {
            // 提醒是否按顺序补位
            this.$confirm('是否按顺序补位?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.addNodeFromCoveringJson(name, id);
            }).catch(() => {
              this.addNodeManually(name, id);
            });
          } else {
            this.addNodeManually(name, id);
          }
        },
        addNodeFromCoveringJson(name, id) {
          // 需要补位，则每次取出补位集合第一个数据进行补位
          const node = this.coveringJson.shift(); // 移除并返回第一个元素
          const nodeId = node.id;
          const nodeIdNum = parseInt(nodeId.replace(/\D/g, ''), 10); // 提取数字并转换为整数
          // 添加节点
          this.$refs.flow.addNode(name, id, nodeIdNum, node.left, node.top);
          var  deleteId = null
          //根据补位的nodeId取出在子表集合中的id，然后再删除的节点工位ID集合中去除
          for (var n=0;n< this.subData.length;n++){
            if(this.subData[n].nodeId === nodeId){
              deleteId = this.subData[n].id
            }
          }
          if(!this.validatenull(deleteId)){
            //从lineTplDetailsDelIds去掉deleteId
            this.lineTplDetailsDelIds.splice(this.lineTplDetailsDelIds.indexOf(deleteId), 1);
          }
          // 画线
          this.drawLinesFromPrevious(nodeIdNum);
          this.drawLinesToNext(nodeIdNum);
        },

        addNodeManually(name, id) {
          let left = 0;
          if ((parseInt(this.nodeCount / 4)) % 2 === 0) {
            left = (this.nodeCount % 4) * 300;
          } else {
            left = ((3 - this.nodeCount % 4) * 300);
          }
          const top = parseInt(this.nodeCount / 4) * 150;
          // 添加节点
          this.$refs.flow.addNode(name, id, this.nodeCount, left, top);
          // 画线
          this.drawLinesFromPrevious(this.nodeCount);
          // 更新节点下标
          this.nodeCount += 1;
        },
        drawLinesFromPrevious(nodeIdNum) {
          const t = this;
          // 从上一个节点到当前节点
          if (t.nodeList.length > 1) {
            const from = `node${nodeIdNum - 1}`;
            const to = `node${nodeIdNum}`;
            t.$nextTick(() => t.$refs.flow.drawLines({ from, to }));
          }
        },
        drawLinesToNext(nodeIdNum) {
          const t = this;
          // 从当前节点到下一个节点
          if (t.nodeList.length-1 !== nodeIdNum) {
            const from = `node${nodeIdNum}`;
            const to = `node${nodeIdNum + 1}`;
            t.$nextTick(() => t.$refs.flow.drawLines({ from, to }));
          }
        },
       /**删除工位*/
        deleteNode(node){
            var id = node.id;
            var t = this;
            this.$confirm("确定要删除工位" + node.name + "?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
                closeOnClickModal: !1
            }).then((function() {
                t.$refs.flow.deleteNode(id);
                //新增数据删除
                if(t.siftWorkPosition(id)) {//判断当前工序是新增还是修改
                    var  deleteId = null
                    //修改数据删除
                    for (var n=0;n< t.subData.length;n++){
                        if(t.subData[n].nodeId === id){
                            deleteId = t.subData[n].id
                        }
                    }
                    if(!t.validatenull(deleteId)){
                        t.lineTplDetailsDelIds.push(deleteId)
                    }
                }
                t.$delete(t.workPositionProcessItem, id); // 删除 workPositionProcessItem 中对应的节点
                let coveringNode = { ...node }
                t.coveringJson.push(coveringNode);
                //补位集合中的数据顺序按照nodeId重新排序
                t.coveringJson.sort((a, b) => parseInt(a.id.replace(/\D/g, ''), 10) - parseInt(b.id.replace(/\D/g, ''), 10));

            })).catch((function() {}))
        },
        /**区分新增工位、修改工位*/
        siftWorkPosition(nodeId){
            var flg = false;//默认新增为false，修改为true
            //循环已添加的工序集合根据节点ID区分新增和修改工序
            for (var n=0;n< this.subData.length;n++){
                if(this.subData[n].nodeId === nodeId){
                    flg=true;
                }
            }
            return flg;
        },
        /**保存修改产线模板*/
        updateRealityLineTpl(){
               if(this.validatenull(this.option.nodeList)){
                this.$message.warning("请选择工位制定产线模板。")
                return;
            }

            //组装需要提交的数据
            var params = {};//参数集合
            params.id = this.lineId;//产线ID
            params.lineName = this.lineName;//产线模板名称
            params.processNodes = JSON.stringify(this.option.nodeList);//工序节点集合（其中mark字段为工序ID）
            params.processNodeLine = JSON.stringify(this.option.lineList);//工序各节点指向顺序集合
            params.coveringJson = JSON.stringify(this.coveringJson);//节点补位集合
            //组装需要提交的数据-产线子表数据组装
            var addObj = [];//需要新增的工位集合
            var editObj = [];//需要修改的工位集合
            //循环工序节点集合
            for (var i = 0; i < this.option.nodeList.length; i++) {
                var obj = {};//创建对象
                var nodeId = this.option.nodeList[i].id;
                var nodeObj = this.option.nodeList[i];
                obj['workPositionId'] = nodeObj.mark;//取出工位ID加入对象
                obj['workPositionName'] = nodeObj.name;//取出工位名称加入对象
                obj['nodeId'] = nodeObj.id;
                obj['lineTplId'] = this.lineId;//产线id

                var workPositionProcessItem = this.workPositionProcessItem[nodeId];
                if(this.validatenull(workPositionProcessItem)){
                  this.$message.warning("请为工位【"+nodeObj.name+"】配置工序。");
                  return;
                }
                obj['workPositionProcessItem'] = JSON.stringify(workPositionProcessItem);//取出工位配置的工序集合加入对象
                var processNameStr="";//工序名字符串
                var processIdStr="";//工序ID字符串
                for (let j = 0; j < workPositionProcessItem.length; j++) {
                    processNameStr = processNameStr + workPositionProcessItem[j].processName + ",";
                    processIdStr = processIdStr + workPositionProcessItem[j].id + ",";
                }
                obj['processNameStr'] = processNameStr.substring(0,processNameStr.length-1);
                obj['processIdStr'] = processIdStr.substring(0,processIdStr.length-1);

                //最后加入提交数据数组
                if (!this.siftWorkPosition(nodeId)) {//判断当前工位是新增还是修改
                    addObj.push(obj);
                } else {//加入提交修改数据数组
                    for (var n = 0; n < this.subData.length; n++) {
                        if (this.subData[n].nodeId === nodeObj.id) {
                            obj['id'] = this.subData[n].id
                        }
                    }
                    editObj.push(obj);
                }
            }
            var data = {
                lineTpl: params,
                addLineTplDetails: addObj,//编辑时新增工位配置集合
                editLineTplDetails: editObj,//编辑时修改工位配置集合
                lineTplDetailsDelIds: this.lineTplDetailsDelIds//编辑时产线模板详情需要删除的ID集合
            }
            this.saveLoading = true;
            //提交
            updateLineTpl(data).then(response => {
                this.$message.success("修改成功。")
                this.$emit('closeTplEdit');//关闭修改页面
                this.saveLoading = false
            }).catch(() => {
                this.saveLoading = false
            });
        },
        //鼠标移到置顶
        handleMouseEnter(nodeId) {
            //属性鼠标移到展开
            // this.$set(this.showActive, nodeId, ['1']);
            let ref = nodeId+"Ref";//获取到当前的ref
            this.$refs[ref].$parent.$refs.node.style.zIndex="999999";
            this.zIndexStyle="1";

        },
        //鼠标移开取消置顶
        handleMouseLeave(nodeId) {
            //属性鼠标移开关闭
            // this.$set(this.showActive, nodeId, []);
            let ref = nodeId+"Ref";//获取到当前的ref
            this.$refs[ref].$parent.$refs.node.style.zIndex="2";
            this.zIndexStyle="";
        },

    }
};
</script>

<style scoped>
  /deep/.avue-flow__node{
    height: auto!important;
  }
  /deep/ .avue-flow__node-header {
    line-height: 40px;
  }
  /deep/.el-descriptions__title {
    font-size: 14px;
    font-weight: 400;
    margin-top: 5px;
  }
 /deep/.el-divider--vertical{
    background-color:#403f3f;
    margin-top: -1px;
  }
 /deep/ .el-dialog-height {
    height: 60vh;
    overflow: auto;
   /* 隐藏默认的滚动条样式 */
    scrollbar-width: none; /* Firefox */
    -ms-overflow-style: none; /* IE and Edge */
}


  /*以下样式是打印的时候avue表格错乱修正方式（主要是序号列和操作列固定影响的）*/
  /deep/.el-table__fixed{
    display: none!important;
  }
  /deep/.el-table__fixed-right{
    display: none!important;
  }
  /deep/.el-table__cell.is-hidden>*{visibility:visible !important;}

  /deep/ .avue-grid{
    display: none!important;
  }
  /deep/.el-main{
    background:#fff !important;
  }
  /deep/.el-card__body{
    padding: 0px!important;
  }
  /*去掉滚动条样式*/
  .demo::-webkit-scrollbar {
    display: none; /* Chrome Safari */
  }
  .demo {
    scrollbar-width: none; /* firefox */
    -ms-overflow-style: none; /* IE 10+ */
    overflow-x: hidden;
    overflow-y: auto;
  }
</style>
